import pygame
import sys
import random
import sqlite3
from pygame import mixer
import os

# 初始化pygame
pygame.init()
mixer.init()

# 屏幕设置
SCREEN_WIDTH = 1280
SCREEN_HEIGHT = 720
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("抽卡模拟器")

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
LIGHT_GRAY = (230, 230, 230)
BLUE = (0, 0, 255)
GOLD = (255, 215, 0)
PURPLE = (128, 0, 128)
RED = (255, 0, 0)
SILVER = (192, 192, 192)
DARK_BLUE = (0, 0, 139)

# 字体
# 替换原来的字体定义
try:
    # 尝试加载文泉驿正黑
    font_small = pygame.font.Font("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 24)
    font_medium = pygame.font.Font("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 32)
    font_large = pygame.font.Font("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 48)
    font_title = pygame.font.Font("/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", 64)
except:
    # 如果找不到，尝试其他字体
    try:
        font_small = pygame.font.Font("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 24)
        font_medium = pygame.font.Font("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 32)
        font_large = pygame.font.Font("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 48)
        font_title = pygame.font.Font("/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", 64)
    except:
        # 最后回退到系统默认字体
        font_small = pygame.font.SysFont('simhei', 24)
        font_medium = pygame.font.SysFont('simhei', 32)
        font_large = pygame.font.SysFont('simhei', 48)
        font_title = pygame.font.SysFont('simhei', 64)

# 卡牌稀有度设置
RARITIES = {
    "普通": {"stars": 1, "color": WHITE, "rate": 75, "fragments": 1},
    "稀有": {"stars": 2, "color": BLUE, "rate": 15, "fragments": 4},
    "罕见": {"stars": 3, "color": PURPLE, "rate": 5, "fragments": 9},
    "史诗": {"stars": 4, "color": GOLD, "rate": 3, "fragments": 16},
    "传说": {"stars": 5, "color": RED, "rate": 2, "fragments": 25}
}

# 卡池设置
CARD_POOLS = {
    "常规池": {
        "currency": "银券",
        "cost": 1,
        "cards": {
            "普通": ["普通卡1", "普通卡2", "普通卡3", "普通卡4", "普通卡5", "普通卡6"],
            "稀有": ["稀有卡1", "稀有卡2", "稀有卡3", "稀有卡4", "稀有卡5", "稀有卡6"],
            "罕见": ["罕见卡1", "罕见卡2", "罕见卡3", "罕见卡4", "罕见卡5", "罕见卡6"],
            "史诗": ["史诗卡1", "史诗卡2", "史诗卡3", "史诗卡4", "史诗卡5", "史诗卡6"],
            "传说": ["传说卡1", "传说卡2", "传说卡3", "传说卡4", "传说卡5", "传说卡6"]
        }
    },
    "特定池1": {
        "currency": "金券",
        "cost": 1,
        "cards": {
            "普通": ["普通卡1", "普通卡2", "普通卡3", "普通卡4", "普通卡5", "普通卡6"],
            "稀有": ["稀有卡1", "稀有卡2", "稀有卡3", "稀有卡4", "稀有卡5", "稀有卡6"],
            "罕见": ["罕见卡1", "罕见卡2", "罕见卡3", "罕见卡4", "罕见卡5", "罕见卡6"],
            "史诗": ["史诗卡1", "史诗卡2", "史诗卡3", "史诗卡4", "史诗卡5", "史诗卡6"],
            "传说": ["传说卡1", "传说卡2", "传说卡3", "传说卡4", "传说卡5", "传说卡6", "特定传说卡1"]
        },
        "target_legend": "特定传说卡1"
    },
    "特定池2": {
        "currency": "金券",
        "cost": 1,
        "cards": {
            "普通": ["普通卡1", "普通卡2", "普通卡3", "普通卡4", "普通卡5", "普通卡6"],
            "稀有": ["稀有卡1", "稀有卡2", "稀有卡3", "稀有卡4", "稀有卡5", "稀有卡6"],
            "罕见": ["罕见卡1", "罕见卡2", "罕见卡3", "罕见卡4", "罕见卡5", "罕见卡6"],
            "史诗": ["史诗卡1", "史诗卡2", "史诗卡3", "史诗卡4", "史诗卡5", "史诗卡6"],
            "传说": ["传说卡1", "传说卡2", "传说卡3", "传说卡4", "传说卡5", "传说卡6", "特定传说卡2"]
        },
        "target_legend": "特定传说卡2"
    }
}

# 合成所需卡牌数量
SYNTHESIS_REQUIREMENT = 5

def init_db():
    conn = sqlite3.connect('gacha.db')
    c = conn.cursor()

    # 创建卡牌收集表（包含所有必要列）
    c.execute('''CREATE TABLE IF NOT EXISTS cards
                 (
                     id     INTEGER PRIMARY KEY AUTOINCREMENT,
                     name   TEXT    NOT NULL,
                     rarity TEXT    NOT NULL,
                     stars  INTEGER NOT NULL,
                     count  INTEGER DEFAULT 1,
                     locked INTEGER DEFAULT 0
                 )''')

    # 兼容性检查：如果表已存在但缺少某些列，则添加
    c.execute("PRAGMA table_info(cards)")
    columns = {column[1] for column in c.fetchall()}

    # 创建抽卡统计表
    c.execute('''CREATE TABLE IF NOT EXISTS stats
                 (
                    id                 INTEGER  PRIMARY KEY AUTOINCREMENT,
                    pool               TEXT     NOT NULL,   
                    total_pulls        INTEGER  DEFAULT  0,
                    normal_pulls       INTEGER  DEFAULT 0,
                    rare_pulls         INTEGER  DEFAULT 0,
                    epic_pulls         INTEGER  DEFAULT 0,
                    legendary_pulls    INTEGER  DEFAULT 0,
                    pity_counter       INTEGER  DEFAULT 0,
                    guaranteed_target  INTEGER  DEFAULT 0
                 )''')

    # 创建资源表
    c.execute('''CREATE TABLE IF NOT EXISTS resources
                 (
                     id INTEGER PRIMARY KEY AUTOINCREMENT,
                     silver_tickets INTEGER DEFAULT 10,
                     gold_tickets   INTEGER DEFAULT 5,
                     fragments  INTEGER DEFAULT 0
                 )''')

    # 初始化资源
    c.execute("SELECT COUNT(*) FROM resources")
    if c.fetchone()[0] == 0:
        c.execute("INSERT INTO resources (silver_tickets, gold_tickets, fragments) VALUES (1000, 500, 0)")

    # 初始化卡池统计
    for pool in CARD_POOLS:
        c.execute("SELECT COUNT(*) FROM stats WHERE pool=?", (pool,))
        if c.fetchone()[0] == 0:
            c.execute("""INSERT INTO stats
                         (pool, total_pulls, normal_pulls, rare_pulls,
                          epic_pulls, legendary_pulls, pity_counter, guaranteed_target)
                         VALUES (?, 0, 0, 0, 0, 0, 0, 0)""", (pool,))

    conn.commit()
    conn.close()

# 资源管理类
class ResourceManager:
    @staticmethod
    def get_resources():
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()
        c.execute("SELECT silver_tickets, gold_tickets, fragments FROM resources LIMIT 1")
        result = c.fetchone()
        conn.close()
        return {
            "silver_tickets": result[0],
            "gold_tickets": result[1],
            "fragments": result[2]
        }

    @staticmethod
    def update_resources(silver=None, gold=None, fragments=None):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()

        query = "UPDATE resources SET "
        params = []

        if silver is not None:
            query += "silver_tickets = ?, "
            params.append(silver)
        if gold is not None:
            query += "gold_tickets = ?, "
            params.append(gold)
        if fragments is not None:
            query += "fragments = ?, "
            params.append(fragments)

        # 移除最后的逗号和空格
        query = query[:-2]

        c.execute(query, params)
        conn.commit()
        conn.close()

    @staticmethod
    def add_fragments(amount):
        current = ResourceManager.get_resources()["fragments"]
        ResourceManager.update_resources(fragments=current + amount)


# 卡牌管理类
class CardManager:
    @staticmethod
    def add_card(name, rarity, stars=1, count=1):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()

        # 检查是否已有该卡牌
        c.execute("SELECT id, count FROM cards WHERE name=? AND stars=?", (name, stars))
        result = c.fetchone()

        if result:
            # 已有该卡牌，增加数量
            card_id, current_count = result
            c.execute("UPDATE cards SET count=? WHERE id=?", (current_count + count, card_id))
        else:
            # 新卡牌，插入记录
            c.execute("INSERT INTO cards (name, rarity, stars, count) VALUES (?, ?, ?, ?)",
                      (name, rarity, stars, count))

        conn.commit()
        conn.close()

    @staticmethod
    def get_card_count(name, stars=None):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()

        if stars is not None:
            c.execute("SELECT SUM(count) FROM cards WHERE name=? AND stars=?", (name, stars))
        else:
            c.execute("SELECT SUM(count) FROM cards WHERE name=?", (name,))

        result = c.fetchone()[0]
        conn.close()
        return result if result else 0

    @staticmethod
    def get_all_cards():
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()
        c.execute("SELECT id, name, rarity, stars, count, locked FROM cards ORDER BY stars DESC, rarity, name")
        cards = c.fetchall()
        conn.close()
        return cards

    @staticmethod
    def lock_card(card_id, lock=True):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()
        c.execute("UPDATE cards SET locked=? WHERE id=?", (1 if lock else 0, card_id))
        conn.commit()
        conn.close()

    @staticmethod
    def decompose_card(card_id):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()

        # 获取卡牌信息
        c.execute("SELECT name, rarity, stars, count FROM cards WHERE id=?", (card_id,))
        card = c.fetchone()

        if not card:
            conn.close()
            return False

        name, rarity, stars, count = card

        # 检查是否已锁定
        c.execute("SELECT locked FROM cards WHERE id=?", (card_id,))
        locked = c.fetchone()[0]

        if locked:
            conn.close()
            return False

        # 计算碎片数量
        fragments = RARITIES[rarity]["fragments"] * count

        # 删除卡牌记录
        c.execute("DELETE FROM cards WHERE id=?", (card_id,))

        # 添加碎片
        ResourceManager.add_fragments(fragments)

        conn.commit()
        conn.close()
        return True

    @staticmethod
    def can_synthesize(name, current_stars):
        return CardManager.get_card_count(name, current_stars) >= SYNTHESIS_REQUIREMENT

    @staticmethod
    def synthesize_card(name, current_stars):
        if not CardManager.can_synthesize(name, current_stars):
            return False

        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()

        # 减少卡牌数量
        c.execute("""
                  UPDATE cards
                  SET count = count - ?
                  WHERE name = ?
                    AND stars = ?
                    AND id IN (SELECT id
                               FROM cards
                               WHERE name = ?
                                 AND stars = ?
                               ORDER BY id
                      LIMIT ?
                      )
                  """, (SYNTHESIS_REQUIREMENT, name, current_stars, name, current_stars, SYNTHESIS_REQUIREMENT))

        # 检查是否有剩余数量为0的卡牌记录
        c.execute("DELETE FROM cards WHERE name=? AND stars=? AND count <= 0", (name, current_stars))

        # 添加高星级卡牌
        new_stars = current_stars + 1
        locked = 1 if new_stars > 5 else 0  # 五星以上自动加锁
        CardManager.add_card(name, RARITIES["传说"]["rarity"] if new_stars >= 5 else RARITIES["史诗"]["rarity"],
                             new_stars)

        # 对新卡牌加锁
        if locked:
            c.execute("UPDATE cards SET locked=1 WHERE name=? AND stars=?", (name, new_stars))

        conn.commit()
        conn.close()
        return True

# 抽卡统计类
class GachaStats:
    @staticmethod
    def get_stats(pool_name):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()
        c.execute(
            "SELECT total_pulls, normal_pulls, rare_pulls, epic_pulls, legendary_pulls, pity_counter, guaranteed_target FROM stats WHERE pool=?",
            (pool_name,))
        result = c.fetchone()
        conn.close()

        if not result:
            return None

        stats = {
            "total_pulls": result[0],
            "normal_pulls": result[1],
            "rare_pulls": result[2],
            "epic_pulls": result[3],
            "legendary_pulls": result[4],
            "pity_counter": result[5],
            "guaranteed_target": result[6]
        }

        # 计算出货率
        if stats["total_pulls"] > 0:
            stats["normal_rate"] = stats["normal_pulls"] / stats["total_pulls"] * 100
            stats["rare_rate"] = stats["rare_pulls"] / stats["total_pulls"] * 100
            stats["epic_rate"] = stats["epic_pulls"] / stats["total_pulls"] * 100
            stats["legendary_rate"] = stats["legendary_pulls"] / stats["total_pulls"] * 100
        else:
            stats["normal_rate"] = 0
            stats["rare_rate"] = 0
            stats["epic_rate"] = 0
            stats["legendary_rate"] = 0

        return stats

    @staticmethod
    def update_stats(pool_name, rarity):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()

        # 更新总抽卡次数
        c.execute("UPDATE stats SET total_pulls = total_pulls + 1 WHERE pool=?", (pool_name,))

        # 更新稀有度计数
        if rarity == "普通":
            c.execute("UPDATE stats SET normal_pulls = normal_pulls + 1 WHERE pool=?", (pool_name,))
        elif rarity == "稀有":
            c.execute("UPDATE stats SET rare_pulls = rare_pulls + 1 WHERE pool=?", (pool_name,))
        elif rarity == "罕见":
            c.execute("UPDATE stats SET rare_pulls = rare_pulls + 1 WHERE pool=?", (pool_name,))
        elif rarity == "史诗":
            c.execute("UPDATE stats SET epic_pulls = epic_pulls + 1 WHERE pool=?", (pool_name,))
        elif rarity == "传说":
            c.execute("UPDATE stats SET legendary_pulls = legendary_pulls + 1 WHERE pool=?", (pool_name,))

        # 更新保底计数器
        if rarity == "传说":
            c.execute("UPDATE stats SET pity_counter = 0, guaranteed_target = 0 WHERE pool=?", (pool_name,))
        else:
            c.execute("UPDATE stats SET pity_counter = pity_counter + 1 WHERE pool=?", (pool_name,))

        conn.commit()
        conn.close()

    @staticmethod
    def set_guaranteed_target(pool_name):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()
        c.execute("UPDATE stats SET guaranteed_target = 1 WHERE pool=?", (pool_name,))
        conn.commit()
        conn.close()

    @staticmethod
    def get_pity_counter(pool_name):
        conn = sqlite3.connect('gacha.db')
        c = conn.cursor()
        c.execute("SELECT pity_counter, guaranteed_target FROM stats WHERE pool=?", (pool_name,))
        result = c.fetchone()
        conn.close()
        return result if result else (0, 0)


# 抽卡逻辑
class GachaSystem:
    @staticmethod
    def draw_card(pool_name, guaranteed=False, target=False):
        pool = CARD_POOLS[pool_name]
        pity_counter, guaranteed_target = GachaStats.get_pity_counter(pool_name)

        # 检查保底
        if pity_counter >= 79 or guaranteed:
            rarity = "传说"
            # 检查是否是大保底
            if guaranteed_target and "target_legend" in pool and target:
                card_name = pool["target_legend"]
            else:
                card_name = random.choice(pool["cards"]["传说"])

            # 更新统计
            GachaStats.update_stats(pool_name, rarity)

            # 添加卡牌
            CardManager.add_card(card_name, rarity, RARITIES[rarity]["stars"])

            return {"name": card_name, "rarity": rarity}

        # 正常抽卡逻辑
        rand = random.randint(1, 100)
        cumulative = 0

        for rarity, info in RARITIES.items():
            cumulative += info["rate"]
            if rand <= cumulative:
                # 从卡池中随机选择一张卡
                card_name = random.choice(pool["cards"][rarity])
                # 更新统计
                GachaStats.update_stats(pool_name, rarity)
                # 自动分解1-2星卡牌
                if info["stars"] <= 2:
                    fragments = info["fragments"]
                    ResourceManager.add_fragments(fragments)
                    return {"name": card_name, "rarity": rarity, "decomposed": True, "fragments": fragments}
                else:
                    # 添加卡牌
                    CardManager.add_card(card_name, rarity, info["stars"])
                    return {"name": card_name, "rarity": rarity}

        # 默认返回普通卡牌
        card_name = random.choice(pool["cards"]["普通"])
        fragments = RARITIES["普通"]["fragments"]
        ResourceManager.add_fragments(fragments)
        return {"name": card_name, "rarity": "普通", "decomposed": True, "fragments": fragments}

    @staticmethod
    def draw_ten(pool_name):
        results = []
        pity_counter, guaranteed_target = GachaStats.get_pity_counter(pool_name)

        # 前9抽
        for _ in range(9):
            results.append(GachaSystem.draw_card(pool_name))

        # 第10抽，如果有保底则触发
        if pity_counter >= 79:
            results.append(GachaSystem.draw_card(pool_name, guaranteed=True))
        else:
            results.append(GachaSystem.draw_card(pool_name))

        return results


# 兑换系统
class ExchangeSystem:
    @staticmethod
    def get_exchange_cost(stars):
        if stars == 3:
            return 20
        elif stars == 4:
            return 45
        elif stars == 5:
            return 80
        elif stars == 6:
            return 125
        elif stars == 7:
            return 625
        return float('inf')  # 无效星级

    @staticmethod
    def can_exchange(stars):
        fragments = ResourceManager.get_resources()["fragments"]
        return fragments >= ExchangeSystem.get_exchange_cost(stars)

    @staticmethod
    def exchange_card(stars):
        if not ExchangeSystem.can_exchange(stars):
            return False

        cost = ExchangeSystem.get_exchange_cost(stars)
        fragments = ResourceManager.get_resources()["fragments"]
        ResourceManager.update_resources(fragments=fragments - cost)

        # 根据星级确定稀有度和卡池
        if stars == 3:
            rarity = "罕见"
            pool_name = "常规池"
        elif stars == 4:
            rarity = "史诗"
            pool_name = "常规池"
        else:  # 5星及以上
            rarity = "传说"
            pool_name = "特定池1"  # 默认选择第一个特定池

        pool = CARD_POOLS[pool_name]
        card_name = random.choice(pool["cards"][rarity])

        # 添加卡牌
        CardManager.add_card(card_name, rarity, stars)

        return {"name": card_name, "rarity": rarity, "stars": stars}


# UI组件
class Button:
    def __init__(self, x, y, width, height, text, color=LIGHT_GRAY, hover_color=GRAY, text_color=BLACK,
                 font=font_medium):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.hover_color = hover_color
        self.text_color = text_color
        self.font = font
        self.is_hovered = False

    def draw(self, surface):
        color = self.hover_color if self.is_hovered else self.color
        pygame.draw.rect(surface, color, self.rect)
        pygame.draw.rect(surface, BLACK, self.rect, 2)

        text_surface = self.font.render(self.text, True, self.text_color)
        text_rect = text_surface.get_rect(center=self.rect.center)
        surface.blit(text_surface, text_rect)

    def check_hover(self, pos):
        self.is_hovered = self.rect.collidepoint(pos)
        return self.is_hovered

    def is_clicked(self, pos, event):
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            return self.rect.collidepoint(pos)
        return False


class CardDisplay:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height)
        self.cards = []
        self.current_page = 0
        self.cards_per_page = 8
        self.card_images = {}  # 缓存加载的图片

        # 预加载卡牌背面图片
        self.card_back = self._load_image("resources/cards/common/back.png")

    def set_cards(self, cards):
        self.cards = cards
        self.current_page = 0

    def _load_image(self, path, scale=1.0):
        """加载并缩放图片"""
        try:
            image = pygame.image.load(path).convert_alpha()
            if scale != 1.0:
                new_size = (int(image.get_width() * scale),
                            int(image.get_height() * scale))
                image = pygame.transform.scale(image, new_size)
            return image
        except:
            # 图片加载失败时创建占位符
            surf = pygame.Surface((150, 200), pygame.SRCALPHA)
            pygame.draw.rect(surf, (100, 100, 100), (0, 0, 150, 200))
            pygame.draw.rect(surf, (200, 200, 200), (0, 0, 150, 200), 2)
            return surf

    def _get_card_image(self, card_name, rarity):
        """获取卡牌图片，如果没有则加载"""
        if card_name not in self.card_images:
            # 根据稀有度确定文件夹
            rarity_folder = {
                "普通": "common",
                "稀有": "rare",
                "罕见": "uncommon",
                "史诗": "epic",
                "传说": "legendary"
            }.get(rarity, "common")

            # 尝试加载图片，使用卡牌名作为文件名
            image_path = f"resources/cards/{rarity_folder}/{card_name}.png"
            print(image_path)
            self.card_images[card_name] = self._load_image(image_path)

        return self.card_images[card_name]

    def draw(self, surface):
        # 绘制背景
        pygame.draw.rect(surface, LIGHT_GRAY, self.rect)
        pygame.draw.rect(surface, BLACK, self.rect, 2)

        # 绘制卡牌
        start_idx = self.current_page * self.cards_per_page
        end_idx = min(start_idx + self.cards_per_page, len(self.cards))

        card_width = 150
        card_height = 200
        margin = 20
        start_x = self.rect.x + margin
        start_y = self.rect.y + margin

        for i, card in enumerate(self.cards[start_idx:end_idx]):
            card_id, name, rarity, stars, count, locked = card
            x = start_x + (i % 4) * (card_width + margin)
            y = start_y + (i // 4) * (card_height + margin)

            # 获取卡牌图片
            card_image = self._get_card_image(name, rarity)

            # 绘制卡牌图片
            surface.blit(card_image, (x, y))

            # 在卡牌上叠加信息
            info_surface = pygame.Surface((card_width, 50), pygame.SRCALPHA)
            info_surface.fill((0, 0, 0, 180))  # 半透明黑色背景

            # 星级显示
            stars_text = font_small.render("★" * stars, True, GOLD if stars >= 3 else BLUE)
            stars_rect = stars_text.get_rect(left=5, centery=25)
            info_surface.blit(stars_text, stars_rect)

            # 数量显示
            count_text = font_small.render(f"×{count}", True, WHITE)
            count_rect = count_text.get_rect(right=card_width - 5, centery=25)
            info_surface.blit(count_text, count_rect)

            # 绘制信息条
            surface.blit(info_surface, (x, y + card_height - 50))

            # 绘制锁定图标
            if locked:
                lock_icon = font_small.render("🔒", True, WHITE)
                lock_rect = lock_icon.get_rect(topright=(x + card_width - 5, y + 5))
                surface.blit(lock_icon, lock_rect)

        # 绘制页码（保持不变）
        total_pages = max(1, (len(self.cards) + self.cards_per_page - 1) // self.cards_per_page)
        page_text = font_small.render(f"第 {self.current_page + 1} 页 / 共 {total_pages} 页", True, BLACK)
        page_rect = page_text.get_rect(center=(self.rect.centerx, self.rect.bottom - 20))
        surface.blit(page_text, page_rect)

# 游戏主界面
class MainMenu:
    def __init__(self):
        self.buttons = [
            Button(SCREEN_WIDTH // 2 - 150, 150, 300, 60, "抽卡"),
            Button(SCREEN_WIDTH // 2 - 150, 230, 300, 60, "卡牌收藏"),
            Button(SCREEN_WIDTH // 2 - 150, 310, 300, 60, "统计"),
            Button(SCREEN_WIDTH // 2 - 150, 390, 300, 60, "退出")
        ]

    def draw(self, surface):
        surface.fill(WHITE)

        # 标题
        title_text = font_title.render("抽卡模拟器", True, BLACK)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, 100))
        surface.blit(title_text, title_rect)

        # 资源显示
        resources = ResourceManager.get_resources()
        silver_text = font_medium.render(f"银券: {resources['silver_tickets']}", True, SILVER)
        gold_text = font_medium.render(f"金券: {resources['gold_tickets']}", True, GOLD)
        fragment_text = font_medium.render(f"通用碎片: {resources['fragments']}", True, PURPLE)

        surface.blit(silver_text, (50, 5))
        surface.blit(gold_text, (250, 5))
        surface.blit(fragment_text, (450, 5))

        # 按钮
        for button in self.buttons:
            button.draw(surface)

    def handle_event(self, event):
        pos = pygame.mouse.get_pos()

        for button in self.buttons:
            button.check_hover(pos)

            if button.is_clicked(pos, event):
                if button.text == "抽卡":
                    return "gacha"
                elif button.text == "卡牌收藏":
                    return "collection"
                elif button.text == "统计":
                    return "stats"
                elif button.text == "退出":
                    return "exit"

        return "main_menu"


# 抽卡界面
class GachaScreen:
    def __init__(self):
        self.pool_buttons = [
            Button(100, 150, 200, 60, "常规池", SILVER),
            Button(350, 150, 200, 60, "特定池1", GOLD),
            Button(600, 150, 200, 60, "特定池2", GOLD)
        ]

        self.draw_buttons = [
            Button(SCREEN_WIDTH // 2 - 250, 400, 200, 80, "单抽"),
            Button(SCREEN_WIDTH // 2 + 50, 400, 200, 80, "十连抽")
        ]

        self.back_button = Button(SCREEN_WIDTH - 150, SCREEN_HEIGHT - 80, 120, 50, "返回")

        self.selected_pool = None
        self.result_cards = []
        self.showing_results = False
        self.result_display = CardDisplay(100, 250, SCREEN_WIDTH - 200, 400)

        # 动画相关
        self.animation_start_time = 0
        self.animation_duration = 1000  # 1秒
        self.animation_cards = []
        self.showing_animation = False

    def draw(self, surface):
        surface.fill(WHITE)

        # 标题
        title_text = font_title.render("抽卡", True, BLACK)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, 80))
        surface.blit(title_text, title_rect)

        # 资源显示
        resources = ResourceManager.get_resources()
        silver_text = font_medium.render(f"银券: {resources['silver_tickets']}", True, SILVER)
        gold_text = font_medium.render(f"金券: {resources['gold_tickets']}", True, GOLD)
        fragment_text = font_medium.render(f"通用碎片: {resources['fragments']}", True, PURPLE)

        surface.blit(silver_text, (50, 5))
        surface.blit(gold_text, (250, 5))
        surface.blit(fragment_text, (450, 5))

        # 卡池选择
        pool_text = font_medium.render("选择卡池:", True, BLACK)
        surface.blit(pool_text, (100, 100))

        for button in self.pool_buttons:
            button.draw(surface)

        # 保底信息
        if self.selected_pool:
            pity_counter, guaranteed_target = GachaStats.get_pity_counter(self.selected_pool)
            pity_text = font_medium.render(f"保底计数: {pity_counter}/80", True, BLACK)
            # surface.blit(pity_text, (SCREEN_WIDTH - 300, 5))
            surface.blit(pity_text, (750, 5))

            if guaranteed_target:
                target_text = font_small.render("下次传说必出目标", True, RED)
                # surface.blit(target_text, (SCREEN_WIDTH - 300, 150))
                surface.blit(target_text, (750, 155))

        # 抽卡按钮
        if self.selected_pool:
            pool_info = CARD_POOLS[self.selected_pool]
            cost_text = font_medium.render(f"消耗: {pool_info['cost']} {pool_info['currency']}", True, BLACK)
            surface.blit(cost_text, (SCREEN_WIDTH // 2 - 100, 220))

            for button in self.draw_buttons:
                # 检查是否有足够的货币
                resources = ResourceManager.get_resources()
                cost = pool_info['cost'] * (10 if button.text == "十连抽" else 1)
                enough = (pool_info['currency'] == "银券" and resources['silver_tickets'] >= cost) or \
                         (pool_info['currency'] == "金券" and resources['gold_tickets'] >= cost)

                button.color = LIGHT_GRAY if enough else (200, 100, 100)
                button.draw(surface)

        # 返回按钮
        self.back_button.draw(surface)

        # 结果显示
        if self.showing_results:
            # 半透明背景
            s = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            s.fill((0, 0, 0, 180))
            surface.blit(s, (0, 0))

            # 结果窗口
            result_rect = pygame.Rect(100, 100, SCREEN_WIDTH - 200, SCREEN_HEIGHT - 200)
            pygame.draw.rect(surface, WHITE, result_rect)
            pygame.draw.rect(surface, BLACK, result_rect, 3)

            # 标题
            result_title = font_large.render("抽卡结果", True, BLACK)
            surface.blit(result_title, (result_rect.centerx - result_title.get_width() // 2, result_rect.y + 20))

            # 卡牌显示
            self.result_display.draw(surface)

            # 关闭按钮
            close_button = Button(result_rect.right - 120, result_rect.bottom - 60, 100, 40, "关闭")
            close_button.draw(surface)

            # 检查鼠标悬停
            pos = pygame.mouse.get_pos()
            close_button.check_hover(pos)

            return close_button

        # 抽卡动画
        # 在GachaScreen类的draw方法中修改动画部分
        if self.showing_animation:
            current_time = pygame.time.get_ticks()
            elapsed = current_time - self.animation_start_time
            progress = min(elapsed / self.animation_duration, 1.0)

            # 半透明背景
            s = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            s.fill((0, 0, 0, 180))
            surface.blit(s, (0, 0))

            # 动画窗口
            anim_rect = pygame.Rect(100, 100, SCREEN_WIDTH - 200, SCREEN_HEIGHT - 200)
            pygame.draw.rect(surface, WHITE, anim_rect)
            pygame.draw.rect(surface, BLACK, anim_rect, 3)

            # 标题
            anim_title = font_large.render("抽卡中...", True, BLACK)
            surface.blit(anim_title, (anim_rect.centerx - anim_title.get_width() // 2, anim_rect.y + 20))

            # 绘制动画卡牌
            card_width = 150
            card_height = 200
            spacing = 20
            total_width = len(self.animation_cards) * card_width + (len(self.animation_cards) - 1) * spacing
            start_x = anim_rect.centerx - total_width // 2
            start_y = anim_rect.centery - card_height // 2

            for i, card in enumerate(self.animation_cards):
                x = start_x + i * (card_width + spacing)
                y = start_y

                # 动画效果
                if progress < 0.2:
                    # 初始阶段，卡牌从上方落下
                    anim_progress = progress / 0.2
                    anim_y = anim_rect.y + 50 + (y - (anim_rect.y + 50)) * anim_progress
                    surface.blit(self.result_display.card_back, (x, anim_y))
                elif progress < 0.8:
                    # 中间阶段，卡牌翻转
                    anim_progress = (progress - 0.2) / 0.6
                    flip_stage = min(anim_progress * 2, 1.0)

                    # 绘制卡背（逐渐消失）
                    if flip_stage < 1.0:
                        back_width = int(card_width * (1 - flip_stage))
                        if back_width > 0:
                            back_part = pygame.transform.scale(
                                self.result_display.card_back,
                                (back_width, card_height)
                            )
                            surface.blit(back_part, (x, y))

                    # 绘制卡面（逐渐显示）
                    if flip_stage > 0:
                        front_width = int(card_width * flip_stage)
                        if front_width > 0:
                            # if "decomposed" in card and card["decomposed"]:
                            #     # 分解的卡牌显示碎片图标
                            #     front_surf = pygame.Surface((front_width, card_height), pygame.SRCALPHA)
                            #     front_surf.fill((200, 200, 200))
                            #     text = font_small.render(f"{card['fragments']}碎片", True, BLACK)
                            #     text_rect = text.get_rect(center=(front_width // 2, card_height // 2))
                            #     front_surf.blit(text, text_rect)
                            # else:
                                # 正常卡牌
                            card_image = self.result_display._get_card_image(card["name"], card["rarity"])
                            front_part = pygame.transform.scale(
                                card_image,
                                (front_width, card_height)
                            )
                            front_surf = pygame.Surface((front_width, card_height), pygame.SRCALPHA)
                            front_surf.blit(front_part, (0, 0))

                            surface.blit(front_surf, (x + card_width - front_width, y))
                else:
                    # 最终阶段，卡牌完全显示
                    if "decomposed" in card and card["decomposed"]:
                        # 分解的卡牌显示碎片图标
                        frag_surf = pygame.Surface((card_width, card_height), pygame.SRCALPHA)
                        frag_surf.fill((200, 200, 200))
                        text = font_medium.render(f"{card['fragments']}碎片", True, BLACK)
                        text_rect = text.get_rect(center=(card_width // 2, card_height // 2))
                        frag_surf.blit(text, text_rect)
                        surface.blit(frag_surf, (x, y))
                    else:
                        # 正常卡牌
                        card_image = self.result_display._get_card_image(card["name"], card["rarity"])
                        surface.blit(card_image, (x, y))

                # 动画结束
                if progress >= 1.0:
                    self.showing_animation = False
                    self.show_results(self.result_cards)

        return None

    def handle_event(self, event):
        pos = pygame.mouse.get_pos()

        # 检查返回按钮
        self.back_button.check_hover(pos)
        if self.back_button.is_clicked(pos, event):
            return "main_menu"

        # 卡池选择
        for button in self.pool_buttons:
            if button.is_clicked(pos, event):
                self.selected_pool = button.text
                self.showing_results = False
                return "gacha"

        # 抽卡按钮
        if self.selected_pool:
            pool_info = CARD_POOLS[self.selected_pool]

            for button in self.draw_buttons:
                button.check_hover(pos)

                if button.is_clicked(pos, event):
                    # 检查资源
                    resources = ResourceManager.get_resources()
                    cost = pool_info['cost'] * (10 if button.text == "十连抽" else 1)

                    if (pool_info['currency'] == "银券" and resources['silver_tickets'] >= cost) or \
                            (pool_info['currency'] == "金券" and resources['gold_tickets'] >= cost):

                        # 扣除资源
                        if pool_info['currency'] == "银券":
                            ResourceManager.update_resources(silver=resources['silver_tickets'] - cost)
                        else:
                            ResourceManager.update_resources(gold=resources['gold_tickets'] - cost)

                        # 执行抽卡
                        if button.text == "单抽":
                            self.result_cards = [GachaSystem.draw_card(self.selected_pool)]
                        else:  # 十连抽
                            self.result_cards = GachaSystem.draw_ten(self.selected_pool)

                        # 显示动画
                        self.showing_animation = True
                        self.animation_start_time = pygame.time.get_ticks()
                        self.animation_cards = self.result_cards.copy()

                        return "gacha"

        # 处理结果窗口
        if self.showing_results:
            close_button = self.draw(screen)
            if close_button and close_button.is_clicked(pos, event):
                self.showing_results = False

        return "gacha"

    # 在GachaScreen类中修改show_results方法
    def show_results(self, cards):
        self.showing_results = True

        # 转换卡牌格式以显示
        display_cards = []
        for card in cards:
            if "decomposed" in card and card["decomposed"]:
                # 已分解的卡牌显示碎片图标
                display_cards.append((
                    -1,  # 虚拟ID
                    f"{card['fragments']}碎片",
                    card["rarity"],
                    RARITIES[card["rarity"]]["stars"],
                    1,  # 数量
                    0  # 未锁定
                ))
            else:
                # 正常卡牌
                display_cards.append((
                    -1,  # 虚拟ID
                    card["name"],
                    card["rarity"],
                    RARITIES[card["rarity"]]["stars"],
                    1,  # 数量
                    0  # 未锁定
                ))

        self.result_display.set_cards(display_cards)


# 卡牌收藏界面
class CollectionScreen:
    def __init__(self):
        self.back_button = Button(SCREEN_WIDTH - 150, SCREEN_HEIGHT - 80, 120, 50, "返回")
        self.prev_button = Button(50, SCREEN_HEIGHT - 80, 120, 50, "上一页")
        self.next_button = Button(200, SCREEN_HEIGHT - 80, 120, 50, "下一页")
        self.lock_button = Button(SCREEN_WIDTH // 2 - 60, SCREEN_HEIGHT - 80, 120, 50, "锁定/解锁")
        self.decompose_button = Button(SCREEN_WIDTH // 2 - 200, SCREEN_HEIGHT - 80, 120, 50, "分解")
        self.synthesize_button = Button(SCREEN_WIDTH // 2 + 80, SCREEN_HEIGHT - 80, 120, 50, "合成")

        self.card_display = CardDisplay(100, 100, SCREEN_WIDTH - 200, SCREEN_HEIGHT - 200)
        self.card_display.set_cards(CardManager.get_all_cards())

        self.selected_card = None

    def draw(self, surface):
        surface.fill(WHITE)

        # 标题
        title_text = font_title.render("卡牌收藏", True, BLACK)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, 50))
        surface.blit(title_text, title_rect)

        # 资源显示
        resources = ResourceManager.get_resources()
        fragment_text = font_medium.render(f"通用碎片: {resources['fragments']}", True, PURPLE)
        surface.blit(fragment_text, (50, 50))

        # 卡牌显示
        self.card_display.draw(surface)

        # 按钮
        self.back_button.draw(surface)
        self.prev_button.draw(surface)
        self.next_button.draw(surface)

        # 选中的卡牌信息
        if self.selected_card:
            card_id, name, rarity, stars, count, locked = self.selected_card

            # 显示详细信息
            info_text = [
                f"名称: {name}",
                f"稀有度: {rarity}",
                f"星级: {stars}",
                f"数量: {count}",
                f"状态: {'已锁定' if locked else '未锁定'}"
            ]

            info_rect = pygame.Rect(SCREEN_WIDTH - 300, 100, 250, 200)
            pygame.draw.rect(surface, LIGHT_GRAY, info_rect)
            pygame.draw.rect(surface, BLACK, info_rect, 2)

            for i, text in enumerate(info_text):
                text_surface = font_small.render(text, True, BLACK)
                surface.blit(text_surface, (info_rect.x + 10, info_rect.y + 10 + i * 30))

            # 显示操作按钮
            self.lock_button.draw(surface)

            # 只有未锁定的卡牌才能分解
            if not locked and stars <= 4:  # 五星以上不能分解
                self.decompose_button.draw(surface)

            # 检查是否可以合成
            if stars < 7 and CardManager.can_synthesize(name, stars):
                self.synthesize_button.draw(surface)

    def handle_event(self, event):
        pos = pygame.mouse.get_pos()

        # 返回按钮
        self.back_button.check_hover(pos)
        if self.back_button.is_clicked(pos, event):
            return "main_menu"

        # 翻页按钮
        self.prev_button.check_hover(pos)
        self.next_button.check_hover(pos)

        if self.prev_button.is_clicked(pos, event):
            self.card_display.prev_page()
        elif self.next_button.is_clicked(pos, event):
            self.card_display.next_page()

        # 卡牌选择
        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            self.selected_card = self.card_display.get_card_at_pos(pos)

        # 锁定/解锁按钮
        if self.selected_card:
            card_id, name, rarity, stars, count, locked = self.selected_card

            self.lock_button.check_hover(pos)
            if self.lock_button.is_clicked(pos, event):
                CardManager.lock_card(card_id, not locked)
                self.card_display.set_cards(CardManager.get_all_cards())
                # 更新选中卡牌状态
                cards = self.card_display.cards
                for card in cards:
                    if card[0] == card_id:
                        self.selected_card = card
                        break

            # 分解按钮
            if not locked and stars <= 4:
                self.decompose_button.check_hover(pos)
                if self.decompose_button.is_clicked(pos, event):
                    if CardManager.decompose_card(card_id):
                        self.card_display.set_cards(CardManager.get_all_cards())
                        self.selected_card = None

            # 合成按钮
            if stars < 7:
                self.synthesize_button.check_hover(pos)
                if self.synthesize_button.is_clicked(pos, event):
                    if CardManager.synthesize_card(name, stars):
                        self.card_display.set_cards(CardManager.get_all_cards())
                        self.selected_card = None

        return "collection"


# 统计界面
class StatsScreen:
    def __init__(self):
        self.back_button = Button(SCREEN_WIDTH - 150, SCREEN_HEIGHT - 80, 120, 50, "返回")
        self.pool_buttons = [
            Button(100, 150, 200, 60, "常规池", SILVER),
            Button(350, 150, 200, 60, "特定池1", GOLD),
            Button(600, 150, 200, 60, "特定池2", GOLD)
        ]
        self.selected_pool = "常规池"

    def draw(self, surface):
        surface.fill(WHITE)

        # 标题
        title_text = font_title.render("抽卡统计", True, BLACK)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, 80))
        surface.blit(title_text, title_rect)

        # 卡池选择
        pool_text = font_medium.render("选择卡池:", True, BLACK)
        surface.blit(pool_text, (100, 120))

        for button in self.pool_buttons:
            button.draw(surface)

        # 统计信息
        stats = GachaStats.get_stats(self.selected_pool)

        if stats:
            # 总抽卡次数
            total_text = font_medium.render(f"总抽卡次数: {stats['total_pulls']}", True, BLACK)
            surface.blit(total_text, (100, 250))

            # 各稀有度出货数量和百分比
            y_offset = 300
            for rarity, info in RARITIES.items():
                count = stats.get(f"{rarity.lower()}_pulls", 0)
                rate = stats.get(f"{rarity.lower()}_rate", 0)

                rarity_text = font_medium.render(
                    f"{rarity}: {count}次 ({rate:.2f}%)",
                    True, info["color"]
                )
                surface.blit(rarity_text, (100, y_offset))
                y_offset += 40

            # 保底计数器
            pity_text = font_medium.render(f"当前保底计数: {stats['pity_counter']}/80", True, BLACK)
            surface.blit(pity_text, (100, y_offset + 20))

            if stats['guaranteed_target']:
                target_text = font_medium.render("下次传说必出目标卡牌", True, RED)
                surface.blit(target_text, (100, y_offset + 60))

        # 返回按钮
        self.back_button.draw(surface)

    def handle_event(self, event):
        pos = pygame.mouse.get_pos()

        # 返回按钮
        self.back_button.check_hover(pos)
        if self.back_button.is_clicked(pos, event):
            return "main_menu"

        # 卡池选择
        for button in self.pool_buttons:
            if button.is_clicked(pos, event):
                self.selected_pool = button.text
                return "stats"

        return "stats"


# 兑换界面
class ExchangeScreen:
    def __init__(self):
        self.back_button = Button(SCREEN_WIDTH - 150, SCREEN_HEIGHT - 80, 120, 50, "返回")
        self.exchange_buttons = [
            Button(100, 200, 200, 60, "兑换3星卡 (20碎片)", PURPLE),
            Button(350, 200, 200, 60, "兑换4星卡 (45碎片)", GOLD),
            Button(600, 200, 200, 60, "兑换5星卡 (80碎片)", RED),
            Button(100, 300, 200, 60, "合成6星卡 (125碎片)", RED),
            Button(350, 300, 200, 60, "合成7星卡 (625碎片)", RED)
        ]
        self.result_card = None
        self.showing_result = False

    def draw(self, surface):
        surface.fill(WHITE)

        # 标题
        title_text = font_title.render("兑换卡牌", True, BLACK)
        title_rect = title_text.get_rect(center=(SCREEN_WIDTH // 2, 80))
        surface.blit(title_text, title_rect)

        # 资源显示
        resources = ResourceManager.get_resources()
        fragment_text = font_medium.render(f"通用碎片: {resources['fragments']}", True, PURPLE)
        surface.blit(fragment_text, (50, 50))

        # 兑换选项
        option_text = font_medium.render("选择兑换选项:", True, BLACK)
        surface.blit(option_text, (100, 160))

        for button in self.exchange_buttons:
            # 检查是否有足够碎片
            stars = 3 if "3星" in button.text else 4 if "4星" in button.text else 5 if "5星" in button.text else 6 if "6星" in button.text else 7
            can_exchange = resources['fragments'] >= ExchangeSystem.get_exchange_cost(stars)

            button.color = button.color if can_exchange else (200, 100, 100)
            button.draw(surface)

        # 返回按钮
        self.back_button.draw(surface)

        # 结果显示
        if self.showing_result and self.result_card:
            # 半透明背景
            s = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            s.fill((0, 0, 0, 180))
            surface.blit(s, (0, 0))

            # 结果窗口
            result_rect = pygame.Rect(SCREEN_WIDTH // 2 - 200, SCREEN_HEIGHT // 2 - 150, 400, 300)
            pygame.draw.rect(surface, WHITE, result_rect)
            pygame.draw.rect(surface, BLACK, result_rect, 3)

            # 标题
            result_title = font_large.render("兑换成功", True, BLACK)
            surface.blit(result_title, (result_rect.centerx - result_title.get_width() // 2, result_rect.y + 20))

            # 卡牌显示
            card_rect = pygame.Rect(result_rect.centerx - 75, result_rect.centery - 50, 150, 200)
            color = RARITIES[self.result_card["rarity"]]["color"] if self.result_card["rarity"] in RARITIES else WHITE
            pygame.draw.rect(surface, color, card_rect)
            pygame.draw.rect(surface, BLACK, card_rect, 2)

            # 卡牌信息
            name_text = font_small.render(self.result_card["name"], True, BLACK)
            surface.blit(name_text, (card_rect.centerx - name_text.get_width() // 2, card_rect.y + 10))

            rarity_text = font_small.render(self.result_card["rarity"], True, BLACK)
            surface.blit(rarity_text, (card_rect.centerx - rarity_text.get_width() // 2, card_rect.y + 40))

            stars_text = font_medium.render("★" * self.result_card["stars"], True,
                                            GOLD if self.result_card["stars"] >= 3 else BLUE)
            surface.blit(stars_text, (card_rect.centerx - stars_text.get_width() // 2, card_rect.y + 70))

            # 关闭按钮
            close_button = Button(result_rect.centerx - 50, result_rect.bottom - 60, 100, 40, "关闭")
            close_button.draw(surface)

            # 检查鼠标悬停
            pos = pygame.mouse.get_pos()
            close_button.check_hover(pos)

            return close_button

        return None

    def handle_event(self, event):
        pos = pygame.mouse.get_pos()

        # 返回按钮
        self.back_button.check_hover(pos)
        if self.back_button.is_clicked(pos, event):
            return "main_menu"

        # 兑换按钮
        resources = ResourceManager.get_resources()

        for button in self.exchange_buttons:
            button.check_hover(pos)

            if button.is_clicked(pos, event):
                stars = 3 if "3星" in button.text else 4 if "4星" in button.text else 5 if "5星" in button.text else 6 if "6星" in button.text else 7

                if resources['fragments'] >= ExchangeSystem.get_exchange_cost(stars):
                    result = ExchangeSystem.exchange_card(stars)
                    if result:
                        self.result_card = result
                        self.showing_result = True
                        return "exchange"

        # 处理结果窗口
        if self.showing_result:
            close_button = self.draw(screen)
            if close_button and close_button.is_clicked(pos, event):
                self.showing_result = False

        return "exchange"


# 主游戏循环
def main():
    init_db()

    # 创建界面
    main_menu = MainMenu()
    gacha_screen = GachaScreen()
    collection_screen = CollectionScreen()
    stats_screen = StatsScreen()
    exchange_screen = ExchangeScreen()

    current_screen = "main_menu"

    clock = pygame.time.Clock()
    running = True

    while running:
        pos = pygame.mouse.get_pos()

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            # 处理当前界面的输入
            if current_screen == "main_menu":
                current_screen = main_menu.handle_event(event)
            elif current_screen == "gacha":
                current_screen = gacha_screen.handle_event(event)
            elif current_screen == "collection":
                current_screen = collection_screen.handle_event(event)
            elif current_screen == "stats":
                current_screen = stats_screen.handle_event(event)
            elif current_screen == "exchange":
                current_screen = exchange_screen.handle_event(event)

            # 从卡牌收藏进入兑换界面
            if current_screen == "collection" and event.type == pygame.KEYDOWN and event.key == pygame.K_e:
                current_screen = "exchange"

        # 绘制当前界面
        if current_screen == "main_menu":
            main_menu.draw(screen)
        elif current_screen == "gacha":
            gacha_screen.draw(screen)
        elif current_screen == "collection":
            collection_screen.draw(screen)
        elif current_screen == "stats":
            stats_screen.draw(screen)
        elif current_screen == "exchange":
            exchange_screen.draw(screen)

        pygame.display.flip()
        clock.tick(60)

    pygame.quit()
    sys.exit()


if __name__ == "__main__":
    main()